﻿using ASmile.Extern.Lib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ASmile.Extern.Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        void PrintLog(string log)
        {
            if (this.InvokeRequired)
            {
                Action<string> Act = PrintLog;
                Invoke(Act, log);
            }
            else
            {
                lbLog.Items.Insert(0, log);
            }
        }

        void LoadConfig()
        {
            try
            {
                var cfg = File.ReadAllText("Config.json");
                Dictionary<string, string> config = JsonHelper.JsonToObject<Dictionary<string, string>>(cfg);
                txtUrl.Text = config["Url"];
                txtType.Text = config["Type"];
            }
            catch (Exception ex)
            {
                MessageBox.Show($"载入配置文件失败，{ex.Message}");
            }
        }

        void LoadInput()
        {
            if (File.Exists("input.json"))
            {
                txtInput.Text = File.ReadAllText("input.json");
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadConfig();
            LoadInput();
        }

        private void btnExec_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> ipt = null;
            if (txtInput.Text.Trim().Length > 0)
            {
                ipt = JsonHelper.JsonToObject<Dictionary<string, string>>(txtInput.Text);
            }
            var r = DataInterface.GetData(txtUrl.Text, txtType.Text, ipt, out string result);
            txtResult.Text = result;
            MessageBox.Show($"{r}");
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            var r = DataInterface.Test(txtUrl.Text);
            MessageBox.Show($"{r}");
        }

        private void btnAsyncExec_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> ipt = null;
            if (txtInput.Text.Trim().Length > 0)
            {
                ipt = JsonHelper.JsonToObject<Dictionary<string, string>>(txtInput.Text);
            }
            DataInterface.GetDataAsync(txtUrl.Text, txtType.Text, ipt,
                ret =>
                {
                    foreach (var item in ret.ExtendData)
                    {
                        PrintLog($"Key: {item.Key} , Value: {item.Value}");
                    }
                    //返回true 继续等待，否则返回flase(下次才能继续)
                    return true;
                });
        }
    }
}